package tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import com.google.inject.Inject;

public class Configurator {

	private Document configDoc;

	@Inject
	public Configurator(@Configpath String configPath)
			throws ValidityException, ParsingException, IOException {
		Builder builder = new Builder();
		File configFile = new File(configPath);
		configDoc = builder.build(configFile);

	}

	public String getProperty(String ref) {
		return getFromPath(ref).getValue();
	}

	public List<String> getListProperty(String ref) {
		Element curElement = getFromPath(ref);
		List<String> result = new ArrayList<>();
		Elements children = curElement.getChildElements();
		for (int i = 0; i < children.size(); i++) {
			result.add(children.get(i).getValue());
		}
		System.out.println("getProp: " + ref);
		System.out.println("getProp - result: " + result);
		return result;
	}

	public Map<String, String> getMapProperty(String ref, String keyName) {
		Map<String, String> result = new HashMap<String, String>();
		Element curElement = getFromPath(ref);
		Elements children = curElement.getChildElements();
		for (int i = 0; i < children.size(); i++) {
			Element e = children.get(i);
			String key = e.getAttribute(keyName).getValue();
			result.put(key, e.getValue());
		}
		return result;
	}
	
	private Element getFromPath(String ref) {
		String[] path = ref.split("\\.");
		Element curElement = configDoc.getRootElement();
		for (String curString : path) {
			curElement = curElement.getFirstChildElement(curString);
		}
		return curElement;
	}
}
